package com.tsyz.servlet.controller;

import com.alibaba.fastjson2.JSON;
import com.tsyz.servlet.domain.dto.req.UserFindByUserNameReqDTO;
import com.tsyz.servlet.domain.dto.resq.UserFindByUserNameRespDTO;
import com.tsyz.servlet.domain.mapstruct.LoginReqDTOMapper;
import com.tsyz.servlet.domain.vo.Result;
import com.tsyz.servlet.domain.vo.req.LoginReqVO;
import com.tsyz.servlet.exception.BusinessException;
import com.tsyz.servlet.exception.ErrorEnumCode;
import com.tsyz.servlet.exception.ParamException;
import com.tsyz.servlet.exception.RpcException;
import com.tsyz.servlet.service.UserService;
import com.tsyz.servlet.util.CookieUtil;
import com.tsyz.servlet.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author ext.zhaoke14
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthApiController extends AbstractController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private CookieUtil cookieUtil;

    /**
     * 处理登录请求
     */
    @PostMapping("/login")
    public Result<String> processLogin(@RequestBody @Valid LoginReqVO loginReqVo, HttpServletResponse response) {
        String logString = "处理登录请求";
        log.info("/auth/login登录请求：{}", JSON.toJSONString(loginReqVo));

        checkParam(loginReqVo);

        try {
            // 验证用户名和密码
            UserFindByUserNameReqDTO userFindByUserNameReqDto = LoginReqDTOMapper.INSTANCE.voToDto(loginReqVo);
            UserFindByUserNameRespDTO respDTO = userService.findByUserName(userFindByUserNameReqDto);
            // 生成Token
            String token = jwtUtil.generateToken(respDTO.getId(), respDTO.getUserName());
            // 设置Token到Cookie
            cookieUtil.setTokenCookie(response, token);
            // 登录成功，返回成功信息和token
            return Result.success("登录成功", token);
        } catch (ParamException e) {
            log.error(logString + ",异常-参数:{},入参:{}", e.getMessage(), JSON.toJSONString(loginReqVo), e);
            return Result.error(e.getCode(), e.getMessage());
        } catch (BusinessException e) {
            log.error(logString + ",异常-业务:{},入参:{}", e.getMessage(), JSON.toJSONString(loginReqVo), e);
            return Result.error(e.getCode(), e.getMessage());
        } catch (RpcException e) {
            log.error(logString + ",异常-远程:{},入参:{}", e.getMessage(), JSON.toJSONString(loginReqVo), e);
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(logString + ",异常-兜底:{},入参:{}", e.getMessage(), JSON.toJSONString(loginReqVo), e);
            return Result.error(ErrorEnumCode.UNKNOWN_ERROR);
        }
    }

    /**
     * 处理登出请求
     */
    @GetMapping("/logout")
    public Result<String> processLogout(HttpServletResponse response) {
        // 删除Token Cookie
        cookieUtil.removeTokenCookie(response);
        return Result.success("登出成功");
    }
}
